package com.vmladenov.cook.core.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

import com.vmladenov.cook.core.Helpers;

public class DatabaseHelper extends SQLiteOpenHelper
{
	private static final String DATABASE_NAME = "cook.db";

	private static String getDbName(Context context)
	{
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)
				|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
		{
			String dbPath = context.getExternalFilesDir(null) + "/" + DATABASE_NAME;
			File file = new File(dbPath);
			if (!file.exists())
			{
				AssetManager manager = context.getAssets();
				try
				{
					InputStream in = manager.open(DATABASE_NAME);
					OutputStream out = new FileOutputStream(dbPath);
					Helpers.copyFile(in, out);
					in.close();
					in = null;
					out.flush();
					out.close();
					out = null;
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			return context.getExternalFilesDir(null) + "/" + DATABASE_NAME;
		}
		return "assets/" + DATABASE_NAME;
	}

	public DatabaseHelper(Context context)
	{
		super(context, getDbName(context), null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
	}

	// @Override
	// public void onCreate(SQLiteDatabase db)
	// {
	// String recipesTableSql = "CREATE TABLE " +
	// GlobalStrings.RECIPES_TABLE_NAME + " ( "
	// + " ID INTEGER PRIMARY KEY," + " URL TEXT," + " IMAGE_URL TEXT," +
	// " TITLE TEXT,"
	// + " PRODUCTS TEXT," + " NOTES TEXT," + " DESCRIPTION TEXT ); ";
	//
	// db.execSQL(recipesTableSql);
	// }
	//
	// @Override
	// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	// {
	// db.execSQL("DROP TABLE IF EXISTS " + GlobalStrings.RECIPES_TABLE_NAME);
	// onCreate(db);
	// }

}
